package com.example.JavaWebApi.core.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 初始化mqtt全局订阅
 */
@Slf4j
@Component
@Conditional(value = {MqttCondition.class})
public class InitSubscribe implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private MqttConfiguration configuration;
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String topicNameAndHandlers=configuration.getTopicNameAndHandlers();
        for(String topicNameAndHandler:topicNameAndHandlers.split(";")){
            String[] arr=topicNameAndHandler.split(":");
            if(arr.length==2){
                String topic=arr[0];
                String handler=arr[1];
                AbstractMqttCallBack handlerBean=applicationContext.getBean(handler,AbstractMqttCallBack.class);
                try {
                    handlerBean.subscribe(topic);
                } catch (MqttException e) {
                    throw new RuntimeException(e);
                }
            }else {
                throw new Error("error topicNameAndHandler");
            }
        }
    }
}
